<script setup lang="ts">
import { useCategoryStore } from '@/store/modules/category';
import { storeToRefs } from 'pinia';
import { AttrAPI, AddOrUpdateAttrAPI, RemoveAttrAPI } from '@/network/product/attr';
import {reactive, ref, watch, nextTick, onBeforeUnmount} from 'vue'
import type { AttrResponseData, AttrList, Attr, AttrValue } from '@/network/product/attr/type';
import { ElMessage } from 'element-plus';
const {c3Id, c2Id, c1Id} = storeToRefs(useCategoryStore())
// 存储所有属性对象
const attrArr = ref<AttrList>([])
// 监视三级分类Id变化
watch(c3Id, async () => {
    // 先清空所有属性对象
    attrArr.value = []
    // 没有三级分类Id，就不发请求
    if (!c3Id.value) return
    getAttr()
})
// 获取三级分类下已有的属性与属性值
async function getAttr() {
    const res: AttrResponseData = await AttrAPI(c1Id.value, c2Id.value, c3Id.value)
    // console.log(res);
    if (res.code === 200) {
        attrArr.value = res.data
    }
}

// 添加属性
// 控制card组件内容切换
const isShow = ref<number>(0)

function addAttr() {
    // 每次点击，先清空数据， 再收集数据
    Object.assign(attrParams, {
        attrName: '',
        attrValueList: [],
        categoryId: c3Id.value, // 三级分类Id
        categoryLevel: 3
    })
    // // 新增属性，收集三级分类Id
    // attrParams.categoryId = c3Id.value
    // 切换结构
    isShow.value = 1
}
// 修改
function updateAttr(row: Attr) {
    isShow.value = 1
    // 把修改的属性呈现到页面上
    // 需用深拷贝，浅拷贝，两个对象之间会互相影响
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 取消按钮
function cancel() {
    isShow.value = 0
}
// 收集新增属性的数据
let attrParams = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '', // 三级分类Id
    categoryLevel: 3
})

// 添加属性值按钮
function addAttrValue() {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true // 控制每一个属性值的编辑模式与查看模式的切换
    })
    // DOM刚渲染拿不到数据
    nextTick(() => {
        // 让组件实例最后一个聚焦
        inputArr.value[inputArr.value.length - 1].focus()
    })
}

// 保存按钮
async function save() {
    const res: any = await AddOrUpdateAttrAPI(attrParams)
    console.log(res);
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: attrParams.id ? '修改成功' : '添加成功'
        })
        getAttr()
        isShow.value = 0
    } else {
        ElMessage({
            type: 'error',
            message: attrParams.id ? '修改失败' : '修改成功'
        })
    }
}

// 文本框失去焦点
function inputBlur(row: AttrValue, $index: number) {
    // 非法情况1：如果文本框为空，我就不让你失去焦点
    if (!row.valueName.trim()) {
        // 删除属性值为空的对象 
        attrParams.attrValueList.splice($index, 1)
        ElMessage({
            type: 'error',
            message: '属性值不能为空'
        })
        return
    }
    // 2 非法情况二：添加新属性值时，去查看所有的属性值对象里有没有和新添加的属性值相同的，如果有，就截取掉这个属性值对象
   const repeat = attrParams.attrValueList.find(item => {
        if (item !== row) { // 注意：需要先排除当前新添加的
            return item.valueName === row.valueName
        }
    })
    // console.log(repeat);
    if (repeat) {
        attrParams.attrValueList.splice($index, 1)
        ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return
    }
    row.flag = false
}
// 切换编辑模式：点击div 就显示文本框
function toEdit(row: AttrValue, $index: number) {
    row.flag = true
    // DOM刚渲染拿不到数据
    nextTick(() => {
        inputArr.value[$index].focus()
    })
    
}

// 准备一个数组，存储对应的组件实例el-input
const inputArr = ref<any>([])

// 删除属性
async function deleteAttr(attrId: number) {
    const res = await RemoveAttrAPI(attrId)
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        // 更新数据
        getAttr()
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}



</script>


<template>
    <div>
        <Category :isShow="isShow"/>
        <el-card style="margin: 10px 0;">
            <div v-show="isShow === 0">
                <el-button v-has="'btn.Attr.add'" @click="addAttr" type="primary" icon="Plus" :disabled="c3Id ? false : true">添加属性</el-button>
                <el-table border style="margin: 10px 0;" :data="attrArr">
                    <el-table-column label="序号" type="index"  align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{row, $index}">
                            <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin: 5px;">{{ item.valueName }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{row, $index}">
                            <el-button v-has="'btn.Attr.update'" @click="updateAttr(row)" type="primary" size="small" icon="Edit"></el-button>
                            <el-popconfirm @confirm="deleteAttr(row.id)" :title="`确定要删除${row.attrName}吗？`" width="200px">
                                <template #reference>
                                    <el-button v-has="'btn.Attr.remove'" type="primary" size="small" icon="Delete"></el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-show="isShow === 1">
                <!-- 添加属性与修改属性的解构 -->
                 <el-form :inline="true">
                    <el-form-item label="属性名称">
                        <el-input v-model="attrParams.attrName" placeholder="请输入属性名称"></el-input>
                    </el-form-item>
                 </el-form>
                 <el-button @click="addAttrValue" :disabled="!attrParams.attrName" type="primary" icon="Plus">添加属性值</el-button>
                 <el-button @click="cancel">取消</el-button>
                 <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
                    <el-table-column type="index" width="80px" label="序号" align="center"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{row, $index}">
                            <el-input :ref="(vc:any) => inputArr[$index] = vc" @blur="inputBlur(row, $index)" v-if="row.flag" v-model="row.valueName" placeholder="请输入属性值" ></el-input>
                            <div @click="toEdit(row, $index)" v-else>{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column width="120px" label="属性值操作" align="center">
                        <template #="{row, $index}">
                            <el-button @click="attrParams.attrValueList.splice($index, 1)" type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-table-column>
                 </el-table>
                 <el-button @click="save" type="primary" :disabled="attrParams.attrValueList.length === 0">保存</el-button>
                 <el-button @click="cancel">取消</el-button>
            </div>
        </el-card>
    </div>
</template>


<style scoped lang='scss'>

</style>